<?php

namespace app\index\model;

use think\Db;
use think\facade\Request;
use think\facade\Session;
use think\Model;

class Shopcart extends Model
{
    function joinshop()
    {
        $a = Session::get("user");
        $input = input();
        if (empty($input)) {
            throw  new \Exception("添加失败！");
            return;
        }
        $bb=Db::query('select * from shopcart WHERE s_id=? AND u_id=?',[$input['id'],$a['id']]);
        if (empty($bb)) {
            $da = ['u_id' => $a, 's_id' => $input['id'], 'math' => 1];
            Db::name('shopcart')->data($da)->insert();
        } else {
            $da = $bb[0]['math'] + 1;
            Db::name('shopcart')->where('s_id', $input['id'])->update(['math' => $da]);
        }
    }
    function xiu(){
        $input=input();
        if (empty($input)) {
            throw  new \Exception("操作失败！");
            return;
        }
        $bb = Db::name('shopcart')->where('s_id', $input['aa'])->find();
        if( $input['math']<$bb['math']){
            $da =$bb['math'] - 1;
            Db::name('shopcart')->where('s_id', $input['aa'])->update(['math' => $da]);
        }else{
            $da =$bb['math'] + 1;
            Db::name('shopcart')->where('s_id', $input['aa'])->update(['math' => $da]);
        }
    }
    function fukuan($id){
        $i = Shopcart::get($id);
        if(empty($i)){
            throw new \Exception('结账失败');
        }else{
            $s=Db::name('htgoods')->where('id',$i['s_id'])->find();
            $grade=Db::name('user')->where('id',$i['u_id'])->find();
            $vip = Db::name('htvip_rule')->where('grade',$grade['grade'])->find();
            $quantity = $i['math']*$s['sale']*$vip['booklet'];
            $time = date("Y-m-d H:i:s");
            $data=['time'=>$time,'money'=>$quantity,'math'=>$i['math'],'u_id'=>$i['u_id'],'s_id'=>$i['s_id']];
            Db::name('list')->insert($data);
            $u=Db::name('integral')->where('u_id',$i['u_id'])->find();
            $b = $s['sale']*$i['math']+$u['integral'];
            Db::name('integral')->where('u_id',$i['u_id'])->update(['integral'=>$b]);
            $dd=Db::name('list')->where('u_id','>',$i['u_id']&'s_id','>',$i['s_id'])->find();
            $aa=Db::name('user')->where('phone',$grade['referee'])->find();
            $v=$aa['yue']+2;
            Db::name('user')->where('id',$aa['id'])->update(['yue'=>$v]);
            $da=['time'=>$time,'type'=>'提成','yue'=>2,'u_id'=>$aa['id']];
            Db::name('details')->insert($da);
        }
        $sj=Db::name('list')->where('u_id','>',$i['u_id']&'s_id','>',$i['s_id'])->find();
        if(empty($sj)){
            throw new \Exception('结账失败');
        }else{
            Db::name('shopcart')->where('s_id',$i['s_id'])->delete();
        }
        return;
    }
}
